<?php
namespace News\Controller;
use Think\Controller;
/**
 * 公共控制器 CommonController.class.php
 */
class CommonController extends Controller{
    /* 属性声明 */
    //企业号corp_id集合数据
    protected $corp_list = null;
    protected $cache_time = 14400;
    protected $all_corp_user = null;

    /* 方法声明 */
    public function __construct() {
        parent::__construct();
        $this -> corp_list = C('CORPID_LIST');
        //初始化redis数据库连接
        $this -> connectRedis();

        //初始化企业号数据
        $data = I('get.');

        /** 调试代码开始 */
        //$corpid = 'wx354598b372f7261a';
        /** 调试代码结束 */

        if(!$corpid = explode('-',$data['state'])[0]){
            $this -> error('未知企业号数据!');
        }

        //企业号数据区域
        $this -> corpid = $corpid;
        $this -> secret = $this -> corp_list[$this->corpid]['secret'];
        $this -> agentid = $this -> corp_list[$this->corpid]['agentid']['News'];

        //初始化企业号accesstoken
        $this -> token = $this -> getAccessToken();
        session('corpid',$this -> corpid);

        //缓存企业号所有成员数据
        $all_user = $this -> cache_all_user();
        $this -> all_corp_user = $all_user;

        //加载到视图
        $this -> assign('all_user_list',json_encode($all_user));

        //通过config接口注入权限验证配置
        require './Org/Chat/jssdk.php';
        $this -> jssdk = new \JSSDK($this -> corpid,$this -> secret);
        $this -> signPackage = $this -> jssdk -> GetSignPackage();
        $this -> assign('signPackage',$this -> signPackage);
        $this -> all_user = $this -> corpid . '_all_user';
        $this -> msg_db_name = $this -> corpid . '_all_messages';
        $this -> userid_name = $this -> corpid . '_userid';
        session('signPackage',$this->signPackage);
    }
    
    /**
     * 生成企业号access_token
     */
    private function getAccessToken(){
        $token_name = $this -> corpid . '_access_token';
        if(!$token = S($token_name)){
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$this->corpid}&corpsecret={$this->secret}";
            $res = json_decode(https_curl($url),true); 
            $token = $res['access_token'];
            S($token_name,$token,7000);
        }
        return $token;
    }
    
    /**
     * 初始化连接redis服务器
     */
    private function connectRedis(){
        $GLOBALS['redis'] = new \Redis();
        if(!$GLOBALS['redis']->connect('127.0.0.1',6379)){
            exit('reids数据库连接失败!');
        }
        if(!$GLOBALS['redis']->auth('wangjun--120304')){
            exit('redis数据库认证登陆失败!');
        }
    }
    
    /**
     * curl模拟http https发起请求
     */
    protected function https_curl($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        //针对ssl https协议
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //检测get post方式提交数据
        if(!empty($data)){
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            //设置post数据
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        //执行命令
        $result = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //返回获得数据
        return $result;
     }

    /**
     * 缓存该企业号下所有成员
     */
    private function cache_all_user(){
        if($all_user = S($this -> corpid.'_all_user')){
            return $all_user;
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={$this->token}&department_id=1&fetch_child=1&status=1";
        $res = json_decode($this -> https_curl($url),true)['userlist'];
        $buffer = array();
        foreach($res as $k => $v){
            $buffer[$k]['userid'] = $v['userid'];
            $buffer[$k]['name'] = mb_substr($v['name'],0,3,'utf-8');
            $buffer[$k]['mobile'] = isset($v['mobile']) ? $v['mobile'] : '';
            $buffer[$k]['position'] = isset($v['position']) ? $v['position'] : '';
            $buffer[$k]['gender'] = isset($v['gender']) ? $v['gender'] : '';
            $buffer[$k]['avatar'] = isset($v['avatar']) ? $v['avatar'].'64' : '';
            $buffer[$k]['department'] = implode(',',$v['department']);
        }
        //缓存数据
        S($this -> corpid.'_all_user',$buffer,$this->cache_time);
        return $buffer;
    }
}